<?php
/**
 * Created by PhpStorm.
 * User: sosyuki
 * Date: 2018/3/19
 * Time: 18:30
 */

namespace Drupal\wx_pay;

use Drupal\easy_wechat\EasyWechatDrupalCache;
use EasyWeChat\Factory;

abstract class EasyWechatApp {

  static function init() {
    $class = new static();
    return $class;
  }

  function getPayment() {
    $config = [
      'app_id' => $this->getAppId(),
      'mch_id' => $this->getMchId(),
      'key' => variable_get('wx_pay_pay_api_key'),

      'cert_path' => $this->getPayCertPath(), // XXX: 绝对路径！！！！
      'key_path' => $this->getPayKeyPath(),      // XXX: 绝对路径！！！！

      'notify_url' => $this->getNotifyUrl(),     // 你也可以在下单时单独设置来想覆盖它
    ];
    if (!empty($this->getRSAKey())) {
      $config = array_merge($config, ['rsa_public_key_path' => $this->getRSAKey()]);
    }
    $app = Factory::payment($config);
    $app['cache'] = new EasyWechatDrupalCache();
    return $app;
  }

  /**
   * @return mixed
   */
  abstract protected function getAppId();

  protected function getMchId() {
    return variable_get('wx_pay_pay_mch_id');
  }

  private function getPayCertPath() {
    $fid = (int) variable_get_value('wx_pay_pay_sslcert');
    if (!empty($fid) && !empty($file = file_load($fid))) {
      $uri = $file->uri;
      return drupal_realpath($uri);
    }
    //watchdog('wx_pay', '支付证书未配置', [], WATCHDOG_WARNING);
    return '';
  }

  private function getPayKeyPath() {
    $fid = (int) variable_get_value('wx_pay_pay_sslkey');
    if (!empty($fid) && !empty($file = file_load($fid))) {
      $uri = $file->uri;
      return drupal_realpath($uri);
    }
    //watchdog('wx_pay', '支付证书未配置', [], WATCHDOG_WARNING);
    return '';
  }

  abstract protected function getNotifyUrl();

  protected function getRSAKey() {
    $fid = (int) variable_get_value('wx_pay_rsa_pem');
    if (!empty($fid) && !empty($file = file_load($fid))) {
      $uri = $file->uri;
      return drupal_realpath($uri);
    }
    //watchdog('wx_pay', 'RSA证书未配置', [], WATCHDOG_WARNING);
    return '';
  }

  protected function makeOutTradeNo() {
    $MchId = $this->getMchId();
    $index = $this->getIndexNumber();
    $Out_trade_no = substr($MchId, 0, 5) . date("YmdHis") . sprintf('%02d', $index) . sprintf('%03d', rand(1, 100));
    return $Out_trade_no;
  }

  protected function getIndexNumber() {
    $old_index = variable_get('wx_pay_pay_index_number', 0);
    if ($old_index > 98) {
      $new_index = 0;
    }
    else {
      $new_index = $old_index + 1;
    }
    variable_set('wx_pay_pay_index_number', $new_index);
    return $old_index;
  }
}
